package order

import (
	"gitee.com/enjoy_5/order-rpc/internal/model/order"
	proto "gitee.com/enjoy_5/order-rpc/proto/order"
	"gorm.io/gorm"
	"time"
)

func OrderPbToModel(in *proto.OrderInfo) *order.Order {
	return &order.Order{
		Model:         gorm.Model{ID: uint(in.OrderId), CreatedAt: time.Unix(in.CreateTime, 0)},
		OrderNo:       in.OrderNo,
		Status:        in.Status,
		PayType:       in.PayType,
		Note:          in.Note,
		AddressId:     in.AddressId,
		UserId:        in.UserId,
		CouponId:      in.CouponId,
		Amount:        in.Amount,
		CommentStatus: in.CommentStatus,
	}
}
func OrderModelToPb(in *order.Order) *proto.OrderInfo {
	return &proto.OrderInfo{
		OrderId:       int64(in.ID),
		CreateTime:    in.CreatedAt.Unix(),
		OrderNo:       in.OrderNo,
		Status:        in.Status,
		PayType:       in.PayType,
		Note:          in.Note,
		AddressId:     in.AddressId,
		UserId:        in.UserId,
		CouponId:      in.CouponId,
		Amount:        in.Amount,
		CommentStatus: in.CommentStatus,
	}
}

// 创建订单
func CreateOrder(in *proto.OrderInfo) (*proto.OrderInfo, error) {
	model := OrderPbToModel(in)
	createOrder, err := model.CreateOrder(in.OrderGoodsInfo)
	if err != nil {
		return nil, nil
	}
	return createOrder, err
}

// 删除订单
func DeleteOrder(id, userId int64) error {
	o := new(order.Order)
	err := o.DeleteOrder(id, userId)
	if err != nil {
		return err
	}
	return nil
}

// 修改订单状态
func UpdateOrderStatus(id, status int64) error {
	o := new(order.Order)
	err := o.UpdateOrderStatus(id, status)
	if err != nil {
		return err
	}
	return nil
}

// 查询订单列表
func GetOrderList(userId, status int64) ([]*proto.OrderInfo, error) {
	o := new(order.Order)
	list, err := o.GetOrderList(userId, status)
	if err != nil {
		return nil, err
	}
	return list, nil
}

// 获取订单详情
func GetOrderInfo(orderid int64) (*proto.OrderInfo, error) {
	o := new(order.Order)
	info, err := o.GetOrderInfo(orderid)
	if err != nil {
		return nil, err
	}
	return OrderModelToPb(info), nil
}

// 回滚创建订单
func RollCreateOrder(orderno string, userid int64) error {
	o := new(order.Order)
	err := o.RolDeleteOrder(orderno, userid)
	if err != nil {
		return err
	}
	return nil
}
